package jalus.dao;

import jalus.model.PMF;
import jalus.model.Tag;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

public class TagDAO {
	@SuppressWarnings("unchecked")
	public Tag getTagByName(String Cid, String tagName){
		PersistenceManager pm = PMF.get().getPersistenceManager();
	    Query query = pm.newQuery(Tag.class);
	    query.setFilter("cid == Cid && name == tagName");
	    query.declareParameters("String Cid, String tagName");
	    List<Tag> tagList;
	    try{
	    	tagList = (List<Tag>) query.execute(Cid, tagName);
	    }finally{
	    	query.closeAll();
	    }
	    if(tagList == null || tagList.isEmpty()){
	    	return null;
	    }
	    return tagList.get(0);
	}

	@SuppressWarnings("unchecked")
	public List<Tag> getAllTag() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
	    Query query = pm.newQuery(Tag.class);
	    List<Tag> tagList;
	    try{
	    	tagList = (List<Tag>) query.execute();
	    }finally{
	    	query.closeAll();
	    }
	    return tagList;
	}
	
	@SuppressWarnings("unchecked")
	public List<Tag> getListByCid(String Cid) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
	    Query query = pm.newQuery(Tag.class);
	    query.setFilter("cid == Cid");
	    query.declareParameters("String Cid");
	    List<Tag> tagList;
	    try{
	    	tagList = (List<Tag>) query.execute(Cid);
	    }finally{
	    	query.closeAll();
	    }
	    return tagList;
	}

	@SuppressWarnings("unchecked")
	public List<Tag> getListByCidOrderByName(String Cid) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
	    Query query = pm.newQuery(Tag.class);
	    query.setFilter("cid == Cid");
	    query.declareParameters("String Cid");
	    query.setOrdering("name desc");
	    List<Tag> tagList;
	    try{
	    	tagList = (List<Tag>) query.execute(Cid);
	    }finally{
	    	query.closeAll();
	    }
	    return tagList;
	}
	
	public void addTag(Tag tag){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			pm.makePersistent(tag);
		}finally{
			pm.close();
		}
	}
	
	public void updateCountByName(String cid, String tagName, int diff) {
		Tag tag = getTagByName(cid, tagName);
		if(tag == null){
			if(diff < 0)return;
			addTag(new Tag(cid, tagName, 1));
		}else{
			PersistenceManager pm = PMF.get().getPersistenceManager();
			tag = (Tag) pm.getObjectById(Tag.class, tag.getId());
			try{
				if(tag.getCount() + diff == 0){
					pm.deletePersistent(tag);
				}else{
					tag.setCount(tag.getCount() + diff);
				}
			}finally{
				pm.close();
			}
		}
	}

	public void delete(Long id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Tag tag = (Tag) pm.getObjectById(Tag.class, id);
		try{
			pm.deletePersistent(tag);
		}finally{
			pm.close();
		}
	}
}
